import { provide ,inject} from 'midway';
import { IUserService,IInsertUser,IGetUser,IDemand } from '../interface';
import { EntityManager } from '../lib/db';
// import { QueryBuilder } from 'knex';
import { IWithPagination } from 'knex-paginate';
@provide('userService')
export class UserService implements IUserService {
  constructor(
    @inject() private readonly em: EntityManager,
  ) {
  }
  /**
   * 新增
   * @param user 用户实体
   */
async insertUser(options?:IInsertUser):Promise<number | undefined> {
  return  this.em.db('users').insert(options).returning('id');
}
async getUser(queryParams:IDemand): Promise<IWithPagination<IGetUser>>{
     // 计算分页参数
    //  const perPage = queryParams.pageSize ? queryParams.pageSize : 10;
    //  const currentPage = queryParams.current ? queryParams.current : 1;
       if(queryParams.openid || queryParams.nickName){
         const openid = queryParams.openid ? `%${queryParams.openid}%` : '';
         const nickName = queryParams.nickName ? `%${queryParams.nickName}%` : '';
            return  this.em.db.with('users',this.em.db.raw(`select * from "users" where ("openid" like '${openid}' or "nick_name" like '${nickName}')`)).select('*').from('users')
        }else{
          return this.em.db('users')
        }

      
}
async fall(): Promise<IGetUser>{
   return this.em.db('users')
}
async delUser(id:number):Promise<number | undefined>{
  return this.em.db('users').where('id',id).del();
}
async putUser(options:IGetUser):Promise<number | undefined>{
  return this.em.db('users').where('id',options.id).update(options);
}
// async chatRecord(options:IChatRecord):Promise<IGetRecord>{
//   const myRecord :IGetRecord = await this.knex('message').where({accountid:options.accountid, oppositeid:options.oppositeid}).select('message.*');
//   const hisRecord:IGetRecord =  await this.knex('message').where({accountid:options.oppositeid, oppositeid:options.accountid}).select('message.*');
//   let friends:IGetRecord={...myRecord,...hisRecord}
//    return new Promise<IGetRecord>(resolve => {
//        resolve(friends);
//    })
// }
}
